Angular bindToController不工作,可以将对象从一个控制器作用域绑定到另一个控制器作用域

时间:2017-02-15 17:55:48

标签: angularjs

我使用的是Angular 1.5.7版本。

我有一个指令,它将控制器名称和视图名称作为字符串,然后分别调用控制器。

我无法将用户名绑定到上一个控制器的调用控制器,我看到我以前的控制器中可用的值。

请问您可以提出什么问题?

    let touch:UITouch = touches.first!
    let positionInScene = touch.location(in: self)
    let touchedNode = self.atPoint(positionInScene)




   if let name = touchedNode.name
    {
        //The first ball that shows up
        if name == "startball"
        {
            print("Touched", terminator: "")
             addBall(ballSize)




            self.addChild(score)
        }
        else if name == "shape"{

            scoreCount += 1

           addBall(ballSize)




            audioPlayer.play()

        }  





    }



    else {

        let scene =  GameOver(size: self.size)
        scene.setMyScore(0)
        let skView = self.view! as SKView
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        scene.size = skView.bounds.size
        scene.setMessage("You Lost!")

        scene.setEndGameMode(va)
        gameTimer.invalidate()
        shownTimer.invalidate()
        print(" timers invalidated ", terminator: "")
        ran = true
        skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25))
    }








    if firstTouch {
        shownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.decTimer), userInfo: nil, repeats: true)
        gameTimer = Timer.scheduledTimer(timeInterval: TIME_INCREMENT, target:self, selector: Selector("endGame"), userInfo: nil, repeats: false)
        firstTouch = false



    }

    if touchCount > 5 {

        for touch: AnyObject in touches {
            let skView = self.view! as SKView
            skView.ignoresSiblingOrder = true
            var scene: Congratz!
            scene =  Congratz(size: skView.bounds.size)
            scene.scaleMode = .aspectFill
            skView.presentScene(scene, transition: SKTransition.doorsOpenHorizontal(withDuration: 1.0))



        }




    }
    touchCount += 1



}




    override func update(_ currentTime: TimeInterval) {
    super.update(currentTime)




}

func endGame(){
    shownTimer.invalidate()
    gameTimer.invalidate()
    let scene =  GameOver(size: self.size)
    scene.setMyScore(scoreCount)
    if let skView = self.view {
        skView.ignoresSiblingOrder = false
        scene.scaleMode = .resizeFill
        scene.size = skView.bounds.size
        scene.setMessage("Times up")

        skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25))
    }

}







       override func addBall(_ size: Int) {
      // Add the ball
      let currentBall = SKShapeNode(circleOfRadius: CGFloat(size))

    let viewMidX = view!.bounds.midX
    let viewMidY = view!.bounds.midY

    currentBall.fillColor = pickColor()



    currentBall.position = randomBallPosition()




    if scoreCount != 0{
        if scoreCount == 1{
            self.addChild(score)
            self.addChild(timeLeftLabel)
            self.childNode(withName: "welcome")?.removeFromParent()
        }
        self.childNode(withName: "ball")?.run(getSmaller)
        self.childNode(withName: "ball")?.removeFromParent()

    }
     currentBall.name = "ball"


    self.addChild(currentBall)
}

     func addSquare(_ size: Int) {
    // Add the square
    let shape = SKShapeNode(rectOf: CGSize(width:CGFloat(size), height:CGFloat(size)))

    shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath

    shape.fillColor = pickColor()

    shape.position = randomBallPosition()

    shape.name = "shape"

    self.addChild(shape)

} 


    func randomBallPosition() -> CGPoint {
    let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1)))
    let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1)))


    return CGPoint(x: xPosition, y: yPosition)

}

2 个答案:

答案 0 :(得分:10)

谢谢 @westor你救了我的一天。我刚刚更新了我的角度并开始得到这个问题,花了很多时间修复它,然后我发现了这个。所以考虑给出一些例子。

在控制器函数中使用 $ onInit 进行绑定范围

controller: function () {
    this.$onInit = function () {

     // your business logic 

    };
};

在我的应用中,我通过范围

进行绑定
myApp.directive('pendingRequests', function () {
  return {
    scope: {
      item:'='
     },
    bindToController: true,
    controller: controller,
    controllerAs: 'vm',
    controller: function ($scope) {
      console.log(this.item); // doesn't logs 

      this.$onInit = function () {
        console.log(this.item); // logs your other directives object
      };
    }
  }
});

使用需要

myApp.directive('pendingRequests', function () {
  return {
    scope: {},
    bindToController: {},
    controller: controller,
    controllerAs: 'pendingReqCtrl',
    require: {
      parent: '^otherDirective'
    },
    controller: function ($scope) {
      console.log(this.parent); // doesn't logs 

      this.$onInit = function () {
        console.log(this.parent); // logs your item object
      };
    }
  }
});

答案 1 :(得分:8)

您是否尝试使用$ onInit初始化代码?

angularjs doc says this

  

弃用警告:虽然绑定非ES6类控制器   目前在控制器构造函数之前绑定到此   在调用时,此用法现已弃用。请放置初始化代码   依赖于控制器上的$ onInit方法内的绑定,   代替。

我更新到1.6.2,我不得不将我的代码放入$ onInit方法来访问绑定。